package com.shanwen.select.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanwen.select.entity.AdminUser;
import com.shanwen.select.entity.Role;
import com.shanwen.select.service.*;

import com.shanwen.select.utils.StringUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.graph.IntegrationGraphServer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin")
@SessionAttributes("adminUser")
public class AdminController {
    @Autowired
    AdminUserService adminUserService;

    @Autowired
    IOrderService orderService;
    @Autowired
    RoleService roleService;
    @Autowired
    WeixinUserInfoSerivice weixinUserInfoSerivice;


    @Autowired
    MenuService menuService;

    /**
     * 用户登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginView(HttpServletRequest request) {
        return "user/index";
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model, String adminName, String passWord, HttpServletRequest request, RedirectAttributes attr, ModelMap modelMap) {
        Map map = new HashMap();

        map.put("adminName", adminName);
        map.put("passWord", passWord);


        UsernamePasswordToken token = new UsernamePasswordToken(adminName, passWord, false);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
            // 此步将 调用realm的认证方法
        } catch (IncorrectCredentialsException e) {
            // 这最好把 所有的 异常类型都背会
            System.out.println("密码错误");
            model.addAttribute("message", "密码错误");
            return "user/index";
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("异常错误，密码校验不成功，可能是sql语句有问题，检查密码");
            model.addAttribute("message", "用户不存在或者被禁用");
            return "user/index";
        }


        //model.addAttribute("title", "sbb");
        //return "redirect:/ocr/list";
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, +1);
        String startDate = sdf.format(calendar.getTime());
        map.put("startDate", startDate);

        calendar.add(Calendar.MONTH, -1);
        String endDate = sdf.format(calendar.getTime());
        map.put("endDate", endDate);

        Map monthResult = orderService.getOrderData(map);
        int count = weixinUserInfoSerivice.count();


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.gt("create_date", endDate);
        int count2 = weixinUserInfoSerivice.count(queryWrapper);


        model.addAttribute("count", count);
        model.addAttribute("count2", count2);
        model.addAttribute("monthResult", monthResult);
        return "user/welcome";

    }


    @RequestMapping(value = "/home")
    public String welcome(HttpServletRequest request, ModelMap modelMap, Model model) {
        //从session中取出当前登录的用户的信息，查询相应的权限。

        Map map = new HashMap();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        calendar.setTime(date);
        String startDate = sdf.format(calendar.getTime());
        map.put("startDate", startDate);

        calendar.add(Calendar.MONTH, -1);
        String endDate = sdf.format(calendar.getTime());
        map.put("endDate", endDate);

        Map monthResult = orderService.getOrderData(map);
        int count = weixinUserInfoSerivice.count();


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.gt("create_date", endDate);
        int count2 = weixinUserInfoSerivice.count(queryWrapper);

        model.addAttribute("count", count);
        model.addAttribute("count2", count2);
        model.addAttribute("monthResult", monthResult);

        return "user/welcome";
    }


    /**
     * 用户注销  未使用，使用的是shiro的默认配置退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();

        subject.logout();
        subject.getSession().removeAttribute("adminUser");
        return "user/index";
    }

    /**
     * 用户修改密码
     */
    @RequestMapping(value = "/editpwd", method = RequestMethod.GET)
    public String editView(ModelMap map, AdminUser user) {
        return "user/editpwd";
    }

    @RequestMapping(value = "/editpwd", method = RequestMethod.POST)
    public String edit(ModelMap map, AdminUser user, String password) throws Exception {
        String adminName = user.getAdminName();
        user.setPassword(StringUtil.getMD5Str(password));
        user.setAdminName(adminName);

        adminUserService.updatePwd(user);
        return "redirect:login";
    }

    /**
     * 超级管理员权限控制（增加用户、删除用户、重置密码，修改用户的状态）
     *
     * @param model
     * @param userpmiss
     * @return
     */
    @RequestMapping(value = "/permission", method = RequestMethod.GET)
    public String personlist(Model model, @Param("adminUser") AdminUser userpmiss) {
        AdminUser adminUser = new AdminUser();
        List<AdminUser> userlist = adminUserService.getList(adminUser);
        model.addAttribute("userlist", userlist);

        return "user/userlist";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addView(Model model) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status", 1);
        List<Role> roleList = roleService.list(queryWrapper);
        model.addAttribute("roleList", roleList);
        return "user/addperson";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(AdminUser adminUser) throws Exception {
        adminUser.setStatus(1);
        adminUser.setPassword(StringUtil.getMD5Str(adminUser.getPassword()));
        adminUserService.savePerson(adminUser);
        return "redirect:permission";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editView(Model model, Integer adminId) {

        AdminUser user = new AdminUser();
        user.setAdminId(adminId);
        user = adminUserService.getList(user).get(0);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status", 1);
        List<Role> roleList = roleService.list(queryWrapper);
        model.addAttribute("roleList", roleList);
        model.addAttribute("user", user);
        return "user/editperson";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(AdminUser adminUser) throws Exception {
        adminUser.setPassword(StringUtil.getMD5Str(adminUser.getPassword()));
        adminUserService.updateUser(adminUser);
        return "redirect:permission";
    }


    /**
     * 删除账户
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(Model model, Integer a) {
        adminUserService.removeById(a);
        return "redirect:permission";
    }

}

